package com.demo.seckill.common.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author libo
 * @ClassName LockDemo
 * @Description: lock和synchronized
 * @date 2018/11/16 14:55
 */
public class LockDemo {
    private static Lock lock = new ReentrantLock();
    private static int num1 = 0;
    private static int num2 = 0;

    /**
     * 本机测试下20万自增基本能确定性能,但是不是特别明显,50万差距还是挺大的
     * 20万以下数据synchronized优于Lock
     * 20万以上数据Lock优于synchronized
     */
    public static void main(String[] args) throws InterruptedException {
        lockDemo();
        syncDemo();
    }

    public static void lockDemo() throws InterruptedException {
        long start = System.currentTimeMillis();
        for (int i=0;i<250000;i++){
            final  int num = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock(num);
                }
            }).start();
        }
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("累加："+num1);
        System.out.println("ReentrantLock锁："+ (end-start));
    }
    public static void syncDemo() throws InterruptedException {
        long start = System.currentTimeMillis();
        for (int i=0;i<250000;i++){
            final  int num = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sync(num);
                }
            }).start();
        }
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("累加："+num2);
        System.out.println("synchronized锁："+ (end-start));
    }

    public static void  lock(int i){
        lock.lock();
        num1 ++;
        lock.unlock();
    }
    public static synchronized void sync(int i){
        num2 ++;
    }

}
